package com.tucc.hello.leetcode.no1_400.no1_200.no1_20.no1_10.no2;

import com.tucc.hello.leetcode.common.ListNode;

/**
 * @author tucc
 * @description todo
 * @package com.tucc.hello.leetcode
 * @date 2021/5/20
 **/
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();

    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        boolean addNext = false;
        ListNode head = null;
        ListNode cur = null;
        while (l1 != null || l2 != null) {
            int n1 = l1 == null ? 0 : l1.val;
            int n2 = l2 == null ? 0 : l2.val;
            int n = n1 + n2;
            if (addNext) {
                n++;
                addNext = false;
            }
            if (n >= 10) {
                n = n - 10;
                addNext = true;
            }
            ListNode node = new ListNode(n);
            if (head == null) {
                cur = head = node;
            } else {
                cur.next = node;
                cur = node;
            }
            l1 = l1 == null ? l1 : l1.next;
            l2 = l2 == null ? l2 : l2.next;
        }
        if(addNext){
            cur.next = new ListNode(1);
        }
        return head;
    }
}
